package com.sky.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.cache.Cache2kBuilderCustomizer;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.support.NoOpCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.concurrent.TimeUnit;

@Configuration
@Slf4j
public class RedisConfiguration {


    // 在 RedisConfiguration 中添加连接异常处理
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate redisTemplate = new RedisTemplate();
        try {
            redisTemplate.setConnectionFactory(redisConnectionFactory);
            redisTemplate.setKeySerializer(new StringRedisSerializer());
        } catch (Exception e) {
            log.error("Redis 不可用", e);
            // 可以在这里设置标记，让业务层知道Redis不可用
        }
        return redisTemplate;
    }

    @Bean
    public CacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory) {
        if (isRedisOn(redisConnectionFactory)) {
            return RedisCacheManager
                    .builder(redisConnectionFactory)
                    .build();
        } else {
            return new NoOpCacheManager();
        }
    }



    private boolean isRedisOn(RedisConnectionFactory cf) {
        try (RedisConnection connection = cf.getConnection()) {
            byte[] pong = connection.ping().getBytes();
            return pong != null && pong.length > 0;
        } catch (Exception e) {
            return false;
        }
    }


}
